package com.tul.exercise.base.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Description 《java编程思想》第22章 示例9：
 *
 * 文本框示例
 **/
public class TextArea extends JFrame{
    // 加载数据按钮
    private JButton b = new JButton("Add Data");
    // 清除数据按钮
    private JButton c = new JButton("Clear Data");

    // 文本输出框
    private JTextArea t = new JTextArea(20, 40);
    private Map<String, String> m = new HashMap<>();

    // 随机计数器
    private Random random = new Random(47);

    public TextArea() {
        m.putAll(createMap());

        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for(Map.Entry me:m.entrySet()) {
                    t.append(me.getKey() + ": " + me.getValue() + "\n");
                }
            }
        });

        c.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText("");
            }
        });

        setLayout(new FlowLayout());
        add(new JScrollPane());
        add(b);
        add(c);
        add(t);
    }

    private Map<String, String> createMap() {
        Map<String, String> result = new HashMap<>();
        result.put("wuhan", "武汉 " + random.nextInt());
        result.put("hushi", "黄石 " + random.nextInt());
        return result;
    }

    public static void main(String[] args) {
        SwingConsole.run(new TextArea(), 475, 425);
    }
}
